package com.flux.utils

import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * 时间转换工具类
 * 为防止线程不安全将静态format进行了锁处理
 * 如遇性能问题可考虑使用ThreadLocal解决
 * Created on 2017/11/1.
 *
 * @author Yang
 */
object TimeUtil {

    private val formatFullDash = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA)
    private val formatFullSlash = SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.CHINA)
    private val formatYMDDash = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)

    /**
     * 下划线格式换为斜线格式
     *
     * @param dashTime 下划线格式字符串
     * @return 斜线格式字符串
     */
    fun DashToSlash(dashTime: String): String {
        val date = ParseFullDash(dashTime)
        return if (date == null) dashTime else FormatFullSlash(date)
    }

    /**
     * 下划线格式字符串转为Date
     *
     * @param dashTime 下划线格式字符串
     * @return Date
     */
    fun ParseFullDash(dashTime: String): Date? {
        synchronized(formatFullDash) {
            return try {
                formatFullDash.parse(dashTime)
            } catch (e: ParseException) {
                e.printStackTrace()
                null
            }
        }
    }

    /**
     * Date转为斜线格式字符串
     *
     * @param date Date
     * @return 斜线格式字符串
     */
    fun FormatFullSlash(date: Date): String {
        synchronized(formatFullSlash) {
            return formatFullSlash.format(date)
        }
    }

    fun formatYMDFromPHP(timeString: String): String {
        val time = timeString.toLong() * 1000
        val date = Date(time)
        synchronized(formatFullSlash) {
            return formatYMDDash.format(date)
        }
    }
}